package net.hn.hnms.biz.shipped.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import net.hn.hnms.biz.shipped.mapper.StatisticMapper;
import net.hn.hnms.biz.shipped.service.IStatisticService;
import net.hn.hnms.biz.shipped.vo.TransportStatisticVO;
import net.hn.hnms.sys.common.core.constant.Constants;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;

/**
 * Created on 2022/9/22.
 *
 * @author ly
 * @desc:
 */
@Service
@DS("master")
public class StatisticServiceImpl implements IStatisticService {


    private StatisticMapper statisticMapper;

    public StatisticServiceImpl(StatisticMapper statisticMapper) {
        this.statisticMapper = statisticMapper;
    }

    /**
     * 运销统计
     *
     * @param date 日期
     * @return TransportStatisticVO
     */
    @Override
    public TransportStatisticVO transportForBigScreen(String date, String mineCode) {
        TransportStatisticVO statisticVO = new TransportStatisticVO();
        Date now = DateUtil.offsetDay(new Date(), -1);
        if (StrUtil.isNotBlank(date)) {
            now = DateUtil.parseDate(date);
        }
        Date yearBegin = DateUtil.beginOfYear(now);
        Date yearEnd = DateUtil.endOfYear(now);


        //日销量
        statisticVO.setDay(statisticMapper.realSaleTotal(mineCode,DateUtil.beginOfDay(now), DateUtil.endOfDay(now)).divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING));
        //月销量
        if(mineCode.equals("620824009734")||mineCode.equals("150781013671")){
            Date nows = DateUtil.date();
            Date lastMonth = DateUtil.offsetMonth(nows, -1);
            System.out.println(lastMonth);
            statisticVO.setMonth(statisticMapper.realSaleTotal(mineCode,DateUtil.beginOfMonth(lastMonth), DateUtil.endOfMonth(lastMonth)).divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING));
        }else{
            statisticVO.setMonth(statisticMapper.realSaleTotal(mineCode,DateUtil.beginOfMonth(now), DateUtil.endOfMonth(now)).divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING));
        }
        //年销量
        statisticVO.setYear(statisticMapper.realSaleTotal(mineCode,yearBegin, yearEnd).divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING));

        //计划年销量
        DynamicDataSourceContextHolder.push("slave");
        BigDecimal planSale = statisticMapper.planSaleTotal(mineCode,yearBegin, yearEnd);
        DynamicDataSourceContextHolder.clear();

        statisticVO.setPercentOfYear(planSale.compareTo(BigDecimal.ZERO) > 0 ?
                statisticVO.getYear().multiply(Constants.HUNDRED).divide(planSale, 2, RoundingMode.CEILING)
                : Constants.ZERO);
        return statisticVO;
    }

}
